package moonhy.c2dm_client;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import moonhy.c2dm_client.dw.ChatData;
import moonhy.c2dm_client.dw.ChatRoomData;
import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

public class C2DMMessageReceiver extends BroadcastReceiver {
	int appVersionCode = 0;
	String service_name = "";
	int room_no = 0;
	String TAG;
	int pageNo		= 0;
	int pageSize	= 30;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		TAG = context.getString(R.string.TAG);
		
		if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
			
			Log.w("C2DM", "Received message");
			
			String msg = "";
			int seqno = 0;
			
			try{
				JSONObject payload = new JSONObject(intent.getStringExtra("payload"));
				if(!payload.isNull("header")){
					
					JSONObject pData = payload.getJSONObject("header");
					
					appVersionCode	= pData.getInt("app_version");
					service_name	= pData.getString("service_name");
					msg				= pData.getString("msg");
					room_no			= pData.getInt("room_no");
					seqno			= pData.getInt("seqno");
					
					Log.d("C2DM", "payload: " + pData.toString());
				}
			}catch(Exception e){
				
			}
			
			///////////////////////////////////////////////////////////////////////////////////////////
			// SharedPreferences 처리
			///////////////////////////////////////////////////////////////////////////////////////////
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			Editor edit = prefs.edit();
			
			if(appVersionCode != prefs.getInt("APP_VERSION_SERVER", 0)){
				edit.putInt("APP_VERSION_SERVER", appVersionCode);
			}
			
			
			if(service_name.equals("push_notice")){
				edit.putInt("noticeMaxSeqno", seqno);
			}else if(service_name.equals("push_chat")){
				new newChatMsgGetter(context, room_no).execute();
			}else if(service_name.equals("push_account")){
				
			}else if(service_name.equals("push_member")){
				
			}
			
			Log.d("C2DM", "appVersionCode ==== " + appVersionCode + "  SharedPreferences Saved Seqno: " + prefs.getInt("noticeMaxSeqno", 0) + "  SharedPreferences current Seqno: " + prefs.getInt("noticeSeqno", 0));
			
			
			edit.commit();
			
			
		}
	}
	
	
	public boolean isMyAppRunningTask(Context context) {
		ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
	    List<RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
	    
		ComponentName topActivity=taskInfo.get(0).topActivity;
		String str=topActivity.getPackageName();
		
		if(str.equals("moonhy.c2dm_client")) {
        	return true;
        }
		return false;
	}
	
	public boolean isMyAppRunning(Context context) {
		ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
	    List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
	    for(int i = 0; i < procInfos.size(); i++){
	        if(procInfos.get(i).processName.equals("moonhy.c2dm_client")) {
	        	Log.d("C2DM", procInfos.get(i).processName);
	        	return true;
	        }
	    }
	    return false;
	}
	public boolean isMyServiceRunning(Context context) {
	    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	    	Log.d("C2DM", service.service.getClassName());
	        if ("moonhy.c2dm_client".equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}

	public void createNotification(Context context, String name, String msg, String service_name, int room_no) {
		String titleText = "";
		int newTabValue = 0;
		if(service_name.equals("push_notice")){
			titleText = "새로운 공지사항이 등록되었습니다.";
			newTabValue = 3;
		}else if(service_name.equals("push_chat")){
			titleText = name + ": " + msg;
			newTabValue = 1;
		}else if(service_name.equals("push_account")){
			
		}else if(service_name.equals("push_member")){
			
		}
		
		
		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.icon, titleText, System.currentTimeMillis());
		notificationManager.cancel(0);
		
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		boolean alarm = false;
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(context, "gline", "chatRoomList");
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				if(jsonObject.getInt("room_no") == room_no){
					if(jsonObject.getInt("alarm") == 0)
						alarm = true;
					else
						alarm = false;
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		if(alarm){
			notification.defaults |= Notification.DEFAULT_VIBRATE;
			notification.defaults |= Notification.DEFAULT_SOUND;
		}
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.putInt("currentTab", newTabValue).commit();
		Intent intent = new Intent(context, TabHostActivity.class);
		
		
		intent.putExtra("payload", msg);
		intent.putExtra("frm_room_no", room_no);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		notification.setLatestEventInfo(context, "규라인", name + ": " + msg, pendingIntent);
		//notification.number = prefs.getInt("UnreadCntTotal", 0);
		notificationManager.notify(0, notification);
	}
	
	
	public class newChatMsgGetter extends AsyncTask<Void, Void, Void>{
		private LinkedList<ChatData> chatJsonData = new LinkedList<ChatData>();
		private Context context;
		SharedPreferences prefs;
		int room_no;
		
		public newChatMsgGetter(Context context, int room_no){
			this.context = context;
			this.room_no = room_no;
			prefs = PreferenceManager.getDefaultSharedPreferences(context);
		}

		@Override
		protected void onPreExecute(){
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			
			try {
				JSONArray json_result;
				json_result = JSONSharedPreferences.loadJSONArray(context, "glineChat", Integer.toString(room_no));
				Log.d(TAG, "[C2DM MSG GET] Init Data ---------------------------------- ");
				for (int i = 0; i < json_result.length(); i++) {
					JSONObject jsonObject = json_result.getJSONObject(i);
					ChatData mList = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
							,jsonObject.getString("name"), jsonObject.getString("content")
							,jsonObject.getString("reg_date")
					);
					chatJsonData.add(mList);
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				String param_seqno = Integer.toString(prefs.getInt("chatMaxSeqno"+room_no, -1));
								
				Map<String, String> map = new HashMap<String, String>();
				map.put("curPageNo", param_seqno);
				map.put("ROOM_NO", Integer.toString(room_no));

				JSONObject json = new JSONObject(hcm.readJSON_GET(context.getString(R.string.SERVER_URL) + "chat/chat_list.php", map));
				JSONArray json_result;
				
				if(json.isNull("data_result")){
					return null;
				}
				
				json_result =	json.getJSONArray("data_result");
				
				Log.d(TAG, "[C2DM MSG GET] New Data Param:::::::::::::: " + param_seqno);
				//chatJsonData.clear();
				for (int i = 0; i < json_result.length(); i++) {
					JSONObject jsonObject = json_result.getJSONObject(i);
					
					ChatData tmp_nd = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
							,jsonObject.getString("name"), jsonObject.getString("content")
							,jsonObject.getString("reg_date")
					);
					chatJsonData.addLast(tmp_nd);
					Log.d(TAG, "[C2DM MSG GET] New Data: " + jsonObject.getInt("seqno"));
				}
				
				Log.d(TAG, "[C2DM MSG GET] THIS WILL BE SAVED:::::::: " + chatJsonData.size());
				
				int initSize = 0;
				if(chatJsonData.size() > pageSize)
					initSize = chatJsonData.size() - pageSize;
				
				JSONArray tmp_result = new JSONArray();
				for(int i = initSize ; i < chatJsonData.size() ; i++){
					JSONObject tmp_hash_result = new JSONObject();
					tmp_hash_result.put("seqno", Integer.toString(chatJsonData.get(i).getSeqno()));
					tmp_hash_result.put("mem_seq", chatJsonData.get(i).getMemId());
					tmp_hash_result.put("name", chatJsonData.get(i).getName());
					tmp_hash_result.put("content", chatJsonData.get(i).getContent());
					tmp_hash_result.put("reg_date", chatJsonData.get(i).getReg_Date());
					tmp_result.put(tmp_hash_result);
				}
				
				Log.d(TAG, "[C2DM MSG GET] Saved Data to Preference: " + tmp_result.toString());
				
				JSONSharedPreferences.remove(context, "glineChat", Integer.toString(room_no));
				JSONSharedPreferences.saveJSONArray(context, "glineChat", Integer.toString(room_no), tmp_result);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
	    }

	    @Override
		protected void onPostExecute(Void unused)
	    {
	    	Editor edit = prefs.edit();
	    	
	    	int seqno = chatJsonData.get(chatJsonData.size()-1).getSeqno();
	    	int totalChatCount	= prefs.getInt("UnreadCntTotal", 1);
	    	int thisChatCount	= prefs.getInt("UnreadCnt"+room_no, 1);
			int prevChatSeqno	= prefs.getInt("chatMaxSeqno"+room_no, seqno);
			int unreadCount = seqno - prevChatSeqno;
	    	
			Log.d(TAG, "[C2DM MSG GET] thisChatCount " + thisChatCount +   "   UnreadCntTotal  " + totalChatCount);
	        edit.putInt("UnreadCnt"+room_no, thisChatCount + unreadCount);
			edit.putInt("UnreadCntTotal",	totalChatCount + unreadCount);
			edit.putInt("chatMaxSeqno"+room_no, seqno);
			//edit.putInt("chatSeqno"+room_no, prefs.getInt("chatMaxSeqno"+room_no,0));
			
			Log.e("C2DM", "[C2DM STAT] unreadCount::::: " + unreadCount + " --  thisChatCount "  + thisChatCount+ " -- ");
			
			edit.commit();
	        
	        if(!isMyAppRunningTask(context)){
	        	createNotification(context, chatJsonData.get(chatJsonData.size()-1).getName(), chatJsonData.get(chatJsonData.size()-1).getContent(), service_name, room_no);
	        }
	    }
	}
}
